/*初始化音视频*/
define(['js/plugins/chat/meeting/tencent/trtc'], function (TRTC) {
    var type = '', LOCALSTREAM, SDKAPPID, userSig, userId, CLIENT, Container, roomTabs, userMap = {};
    var Meet = {
        init: function (initParam, roomId, userName, container) {
            if (!CLIENT) {
                Container = container;
                roomTabs = $('.videoDialog .roomTabs', Container).tabs({
                    heightStyle: "fill"
                });
                userMap[roomId] = userName;
                type = initParam.type;
                SDKAPPID = parseInt(initParam.appId);
                const SECRETKEY = initParam.appSecret;
                // a soft reminder to guide developer to configure sdkAppId/secretKey
                if (SDKAPPID === '' || SECRETKEY === '') {
                    alert(
                        '请先配置好您的账号信息： SDKAPPID 及 SECRETKEY ' +
                        '\r\n\r\nPlease configure your SDKAPPID/SECRETKEY in js/debug/GenerateTestUserSig.js'
                    );
                }
                userId = $E.staff.id;
                var expire = 604800;
                // var currtime = new Date().getTime(), str =  userId + SDKAPPID + currtime + expire;
                // var hash = CryptoJS.HmacSHA256("Message", str);
                // usersig = CryptoJS.enc.Base64.stringify(hash);
                userSig = 'eJwtzMEKgkAUheF3mW0hdybv2AgtykkIyqgEsV3hGJeo1IayonfP1OX5DvwfFi93zsNUzGfCATZsN2XmaimnlhczWKm0f*7Z*VAUlDGfuwBSInpe95i6oMo0jogCADq1dPmbRBihi2O3r9CpCcf7oI6PGx5E6VuEptzOteL0VKUW0eCVWF6a3IbTm17DhH1-8lwwlA__';
                // setup logging stuffs
                TRTC.Logger.setLogLevel(TRTC.Logger.LogLevel.DEBUG);

                CLIENT = TRTC.createClient({
                    mode: 'rtc',
                    sdkAppId: SDKAPPID,
                    userId: userId,
                    userSig: userSig
                });
                CLIENT.on('stream-added', event => {
                    const remoteStream = event.stream;
                    $F.log('远端流增加: ' + remoteStream.getId());
                    $('.chat .chat_audio', Container).show();
                    $('.chat .chat_video', Container).show();
                    let roomId = remoteStream.client_.roomId_;
                    Meet.showVideoAndAudioDialog(roomId, remoteStream, function () {
                        CLIENT.subscribe(remoteStream);
                    });
                });

                CLIENT.on('stream-subscribed', event => {
                    const remoteStream = event.stream;
                    $F.log('远端流订阅成功：' + remoteStream.getId());
                    // 播放远端流
                    remoteStream.play('client-video-box');
                    $("#client-video-box").show();
                });

                CLIENT.on('peer-join', event => {
                    const userId = event.userId;
                    $F.log("用户 [s%] 进入房间", userId);
                });

                CLIENT.join({
                    roomId: parseInt(roomId)
                });
                $F.log('Chat - tencent video', 'join chat success');
            } else {
                CLIENT.join({
                    roomId: parseInt(roomId)
                });
                $F.log('Chat - tencent video', 'join chat success');
            }
        },
        /**
         * 显示聊天请求接受对话框
         */
        showVideoAndAudioDialog: function (roomId, remoteStream, callBack) {
            if ($('.chat', Container).width() === 0) {
                $E.openChatPanel();
                $('.chat', Container).show();
            }

            $('.videoDialog', Container).show().css({
                "paddingTop": ($(Container).height() - $('.videoDialog .chat-dialog-content', Container).height() - 100) / 2
            });
            var nav = roomTabs.find(".ui-tabs-nav"), m = 'request_' + roomId,
                label = (remoteStream.hasVideo() ? '视频' : '语音') + '[' + roomId + ']',
                tab = $("<li data-id='" + roomId + "'><a href='#" + m + "'>" + label + "</a></li>"),
                tabContainer = $('<div id="' + m + '" class="request-tab-container" style="padding: 10px;"></div>');
            tabContainer.append(
                '<div class="dialog_bd">' +
                '<div><table>' +
                '<tr>' +
                '<td>来自</td><td>' + userMap[roomId] + '的' + (remoteStream.hasVideo() ? '视频' : '语音') + '请求</td>' +
                '</tr>' +
                '</table></div>' +
                '</div>' +
                '<div class="dialog_ft">' +
                '<a href="javascript:;" class="btn btn_primary acceptVCall">接收</a>' +
                '<a href="javascript:;" class="btn btn_primary refeuseVCall">拒绝</a>' +
                '</div>');

            // 视频接通
            $('.acceptVCall', tabContainer).one('click', function (e) {
                e.stopPropagation();
                //订阅远端流
                closeRequestTab(tab);
                $F.log('Chat - meeting', 'acceptCall');
                $('.meeting.videoMeet, .meeting.videoMeet .video', Container).show();
                $('.meeting.videoMeet .audio', Container).hide();

                Meet.joinCall(remoteStream.hasVideo());
                callBack();
            });
            //视频挂断
            $('.refeuseVCall', tabContainer).one('click', function (e) {
                e.stopPropagation();
                closeRequestTab(tab);
                // 拒绝接收该远端流所包含的任何音视频数据
                CLIENT.unsubscribe(remoteStream).catch(e => {
                    $F.error('failed to unsubscribe remoteStream');
                });
            });

            tab.data('container', tabContainer);
            tab.appendTo(nav);
            roomTabs.append(tabContainer);

            function closeRequestTab(tab, requestId) {
                tab.data("container").remove();
                tab.remove();
                roomTabs.tabs("refresh");
                if ($('li', nav).length === 0) {
                    $('.videoDialog', Container).hide();
                }
            }
        },
        joinCall: function (type) {
            try {
                if (LOCALSTREAM) {
                    CLIENT.unpublish(LOCALSTREAM);
                }
                LOCALSTREAM = TRTC.createStream({userId, audio: true, video: type});
                try {
                    // initialize the local stream and the stream will be populated with audio/video
                    LOCALSTREAM.initialize();
                    $F.log('initialize local stream success');

                    LOCALSTREAM.on('player-state-changed', event => {
                        $F.log(`local stream ${event.type} player is ${event.state}`);
                    });
                } catch (error) {
                    $F.error('failed to initialize local stream - ' + error);
                    switch (error.name) {
                        case 'NotReadableError':
                            $F.alert('暂时无法访问摄像头/麦克风，请确保系统允许当前浏览器访问摄像头/麦克风，并且没有其他应用占用摄像头/麦克风')
                            return;
                        case 'NotAllowedError':
                            if (error.message === 'Permission denied by system') {
                                $F.alert('请确保系统允许当前浏览器访问摄像头/麦克风');
                            } else {
                                $F.log('User refused to share the screen');
                            }
                            return;
                        case 'NotFoundError':
                            $F.alert(
                                '浏览器获取不到摄像头/麦克风设备，请检查设备连接并且确保系统允许当前浏览器访问摄像头/麦克风'
                            );
                            return;
                        default:
                            return;
                    }
                }
                LOCALSTREAM
                    .initialize()
                    .then(() => {
                        $F.log('初始化本地流成功');
                        // 'local_stream' 是在 DOM 中的一个 div 标签的 ID
                        $("#self-video-box").html('');
                        LOCALSTREAM.play('self-video-box');
                        CLIENT
                            .publish(LOCALSTREAM)
                            .then(() => {
                                $F.log('Chat - tencent video', '本地流发布成功');
                            })
                            .catch(error => {
                                $F.err('Chat Tencent Video Accept Call' + error.message);
                            });
                    })
                    .catch(error => {
                        $F.error('初始化本地流失败 ' + error.message);
                    });

            } catch (error) {
                $F.err('Failed To Publish Local Stream - ' + error.message);
            }
        },
        leaveCall: function () {
            // 关闭摄像头
            if (LOCALSTREAM) {
                var videoTrack = LOCALSTREAM.getVideoTrack();
                if (videoTrack) {
                    LOCALSTREAM.removeTrack(videoTrack)
                    // 停止采集，关闭摄像头
                    videoTrack.stop();
                }
                // 关闭麦克风
                LOCALSTREAM.muteAudio();
                const audioTrack = LOCALSTREAM.getAudioTrack();
                if (audioTrack) {
                    audioTrack.stop();
                }
            }

            $('#selfvideo', Container).hide();
            $('#othervideo', Container).hide();
            $('.meeting', Container).hide();
            // CLIENT
            //     .leave()
            //     .then(() => {
            //         // 退房成功，可再次调用client.join重新进房开启新的通话。
            //         $F.log('Chat Tencent Video Leave Call', '退出房间成功');
            //
            //     })
            //     .catch(error => {
            //         // 错误不可恢复，需要刷新页面。
            //         $F.err('Chat Tencent Video Leave Call 退房失败, 错误不可恢复，需要刷新页面' + error.message);
            //     });
        }
        ,
        rejectCall: function () {
            CLIENT.leave().then(() => {
                // leaving room success
            }).catch(error => {
                $F.err('Chat Tencent Video Reject Call' + error.message);
            });
        }
    }
    /*音视频*/

    // 视频接通
    $('.acceptVCall', Container).click(function (e) {
        e.stopPropagation();
        Meet.acceptCall();
    });
    //视频挂断
    $('.releaseVCall', Container).click(function (e) {
        e.stopPropagation();
        Meet.leaveCall();
    });

    return {
        loadTencentMeet: Meet.init,
        joinCall: Meet.joinCall
    };
});